<template>
  <div>
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button style="float:right; margin-right: 30px" type="success" @click="showUploadModal = true">
          导入
        </el-button>
        <el-button style="float:right; margin-right: 30px" type="primary" @click="handleSearch()">
          查询
        </el-button>
        <el-button style="float:right; margin-right: 15px" @click="handleResetSearch()">
          重置
        </el-button>
      </div>
      <el-dialog title="文件上传(请只选择一个.xls/.xlsx文件)" v-model="showUploadModal">
        <div>
          <el-upload ref="upload" drag :before-upload="beforeUpload" :on-change="handleChange"
                     :on-remove="handleRemoveChange"
                     :on-exceed="handleListExceed" :http-request="importExcel" :on-preview="handlePreview"
                     :auto-upload="false" :limit="1">
            <div style="margin-bottom: 12px; text-align: center;">
              <i class="el-icon-upload"></i>
              <p style="font-size: 16px; margin: 10px 0;">点击或者拖动文件到该区域来上传</p>
            </div>
          </el-upload>

          <div style="width: 100%; margin-top: 30px; display: flex; justify-content: center;">
            <el-button type="success" @click="handleClick" :disabled="UpLoadDisabled">
              上传
            </el-button>
          </div>
        </div>
      </el-dialog>
      <el-dialog title="上传信息一览" v-model="showUpTableModal" :close-on-press-escape="false"
                 :close-on-click-modal="false"
                 @close="handleClose" width="1200px" @update:visible="confirmClose">
        <ConfirmTable
            :uuid="uploadConfirmData?.uuid"
            :successList="uploadConfirmData?.successList"
            :failList="uploadConfirmData?.failList"
            @close="handleConfirmTableClose"/>
      </el-dialog>
      <div style="margin-top: 30px; ">
        <el-form style="display: inline-block;">
          <!-- <el-form :inline="true" :model="listQuery" size="small" label-width="140px"> -->
          <div style="display: inline-block;margin-left:20px">
            <el-form-item label="输入搜索：">
              <el-input v-model="queryParams.stallNum" class="input-width" placeholder="档口号" clearable></el-input>
            </el-form-item>
          </div>
          <div style="display: inline-block;margin-left:20px">
            <el-form-item label="店铺名称：">
              <el-input v-model="queryParams.shopName" class="input-width" placeholder="店铺名称" clearable></el-input>
            </el-form-item>
          </div>
          <div style="display: inline-block;margin-left:20px">
            <el-form-item label="店长姓名：">
              <el-input v-model="queryParams.shopOwner" class="input-width" placeholder="店长姓名" clearable></el-input>
            </el-form-item>
          </div>

        </el-form>
      </div>
    </el-card>
  </div>
  <div class="table-container">
    <el-table :data="tableData.list" ref="multipleTable" tooltip-effect="dark" border style="width: 100%" stripe>
      <el-table-column prop="shopName" label="商家名称" align="center" width="150px"/>
      <el-table-column prop="areaNum" label="区域" align="center" width="100px"/>
      <el-table-column prop="stallNum" label="档口号" align="center" width="150px"/>
      <el-table-column prop="shopOwner" label="店长" align="center" width="150px"/>
      <el-table-column prop="mobile" label="店长联系方式" align="center" width="150px"/>
      <el-table-column label="备注" align="center" width="220px">
      </el-table-column>
      <el-table-column fixed="right" label="操作" class="operate-button-container" align="center">
        <template #default="{row}">
          <el-button size="small" @click="clickDetail(row)" color="#626aef" :dark="isDark">
            详情
          </el-button>
          <el-button type="success" size="small" @click="clickUser(row)">
            添加用户
          </el-button>
          <el-button type="warning" size="small" @click="dialogTableVisible3 = true">
            编辑
          </el-button>
          <el-button type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="商户详情" width="1200" v-model="dialogTableVisible1">
      <el-table :data="[proData]">
        <el-table-column prop="mobile" style="width: 140px;" label="店铺绑定手机号"/>
        <el-table-column prop="intro" label="店铺简介"/>
        <el-table-column prop="shopLogo" label="店铺logo"/>
        <el-table-column prop="openTime" label="每天营业时段"/>
        <el-table-column prop="province" label="店铺所在省份"/>
        <el-table-column prop="city" label="店铺所在城市"/>
        <el-table-column prop="area" label="店铺所在区域"/>
        <el-table-column prop="stallNum" label="档口号"/>
        <el-table-column prop="createTime" label="注册时间" :formatter="formatCreateTime"/>
      </el-table>
    </el-dialog>
    <el-dialog title="添加用户" width="600" v-model="addUserInfo">
      <el-form ref="formRef" :model="addForm" :rules="rules">
        <!-- <el-form-item prop="gender" label="性别：">
          <el-input v-model="addForm.gender" v-if="addForm.gender==0">男</el-input> 
        </el-form-item> -->
        <el-form-item label="性别：" prop="gender">
          <el-radio-group v-model="addForm.gender">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="idNumber" label="身份证号：">
          <el-input v-model="addForm.idNumber"/>
        </el-form-item>
        <el-form-item prop="icon" label="头像：">
          <el-input type="number" v-model="addForm.icon"/>
        </el-form-item>
        <el-form-item prop="nickName" label="昵称：">
          <el-input v-model="addForm.nickName"/>
        </el-form-item>
        <el-form-item prop="phone" label="联系方式：">
          <el-input v-model="addForm.phone"/>
        </el-form-item>
        <el-form-item prop="userName" label="用户名：">
          <el-input v-model="addForm.userName"/>
        </el-form-item>
        
      </el-form>
      <el-button type="primary" style="margin-left: 50%;" @click="save()">提交</el-button>
    </el-dialog>
  </div>
  <el-pagination size="default" style="float: right;margin-top: 5px" background
                 layout="total, sizes, prev, pager, next"
                 @change="handleSearchPaginationChange"
                 :total="Number(tableData.total)"
                 v-model:current-page="queryParams.pageNum"
                 v-model:page-size="queryParams.pageSize"
                 v-model:page-sizes="allocateUserPageSizes"/>
  <!--  <el-pagination-->
  <!--      v-model:currentPage="queryParams.pageNum"-->
  <!--      background-->
  <!--      layout="prev, pager, next, total, sizes"-->
  <!--      :current-page="queryParams.pageNum"-->
  <!--      :page-size="queryParams.pageSize"-->
  <!--      :total="tableData.total"-->
  <!--      @current-change="handleCurrentChange"-->
  <!--      @size-change="handleSizeChange"-->
  <!--  />-->
</template>

<script setup>

import {ref, reactive, onMounted, VueElement} from 'vue'
import {ElMessage} from 'element-plus';
import {getShop,} from '../../../api';
import ConfirmTable from './confirmTable.vue';
import {importVerify} from '../../../api';
import {getShopByPage, getShopDetail,addShopUser} from '../../../api';
import { ro } from 'element-plus/es/locales.mjs';
// import func from '../../../../vue-temp/vue-editor-bridge';

const formLabelWidth = '140px'

const model = defineModel()

const dialogTableVisible1 = ref(false)

const dialogTableVisible2 = ref(false)

const dialogTableVisible3 = ref(false)

//数据表数据
const tableData = reactive({
  list: [],
  pageNum: '',
  pageSize: '',
  total: "",
  totalPage: ''
})
onMounted(() => {
  getData();
  handleSearch();
});

//查询
const handleSearch = async () => {
  // console.log('查询内容1', queryParams.value)
  // let res = await getShopByPage(queryParams.value)
  // console.log('查询内容', res.data)
  // tableData.list = res.data.list;
  // console.log("111")
  // console.log('返回数据', tableData.list)
  // console.log("222")
  //console.log('查询结果', tableData.list.value)
  getData()

}
// 当前页变化处理
const handleCurrentChange = (val) => {

  queryParams.pageNum = val; // 更新当前页码
  getData();// 重新获取数据
};

// 页面大小变化处理
const handleSizeChange = (val) => {
  queryParams.pageSize = val; // 更新每页条目数
  getData(); // 重新获取数据
};

const handleSearchPaginationChange = () => {
  getData();
}

let proData = ref({
  mobile: '',
  intro: '',
  shopLogo: '',
  openTime: '',
  city: '',
  area: '',
  stallNum: '',
  createTime: '',
})

const clickDetail = (row) => {
  dialogTableVisible1.value = true
  console.log('res', row)
  //let res = getShopDetail(row.id)
  //console.log('res23456',res.value)
  proData.value = row

}
const formatCreateTime = (row, column, cellValue) => {
  if (cellValue) {
    const date = new Date(cellValue);
    return date.toLocaleString(); // 或者根据具体需求进行格式化
  }
  return '';
};

//添加用户
const addForm = ref({
  gender: 0,
  groupId: 0,
  icon: '',
  idNumber: '',
  nickName: '',
  password: null,
  phone: '',
  roleId: 0,
  shopId:0,
  shopInfo: {
    areaNum: '',
    shopName: '',
    shopOwner: '',
    shopPhone: '',
    shopSn: '',
    stallNum: ''
  },
  userName: '',
  wxCode: ''
})
const addUserInfo = ref(false)
const clickUser = async(row) =>{
addUserInfo.value = true
console.log('row',row)
console.log('addForm.value.shopInfo',addForm.value.shopInfo)
// addForm.value.shopInfo = row
addForm.value.shopId = row.id
addForm.value.shopInfo.areaNum = row.areaNum
addForm.value.shopInfo.shopName = row.shopName
addForm.value.shopInfo.shopOwner = row.shopOwner
addForm.value.shopInfo.shopPhone = row.mobile
addForm.value.shopInfo.shopSn = row.shopSn
addForm.value.shopInfo.stallNum = row.stallNum
console.log('addForm.shopId',addForm.value.shopId )
console.log('addForm.shopInfo ',addForm.value.shopInfo )
console.log('addForm.value',addForm.value)
addForm.value.roleId = '10'
addForm.value.groupId = null
addForm.value.wxCode = null
addForm.value.password = null
}

const save = async() =>{
 console.log('addForm.value.phone',addForm.value.phone  )
 console.log('addForm.value.shopInfo',addForm.value.shopInfo  )
  let res=await addShopUser(addForm.value)
if (res.code==200){
  ElMessage.success("保存成功！")
}else{
  ElMessage({
      message: res.message,
      type: 'error',
      duration: 1000
    });
}
}

//重置
const handleResetSearch = async () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    // account: "",
    stallNum: '',
    areaNum: '',
    intro: '',
    shopId: '',
    shopName: '',
    shopOwner: '',
    shopType: ''
  };
  getData();
}


//批量导入
const showUploadModal = ref(false)
const showUpTableModal = ref(false);
const fileList = ref([]);
const upload = ref(null);
let queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  // account: "",
  stallNum: '',
  areaNum: '',
  intro: '',
  shopId: '',
  shopName: '',
  shopOwner: '',
  shopType: ''
});

const handleConfirmTableClose = () => {
  notNoticeClose.value = true;
  showUpTableModal.value = false;
  getData();
};

const getData = () => {
  getShopByPage(queryParams.value)
      .then((response) => {
        tableData.list = response.data.list;
        console.log('dangqiande', response.data)
        tableData.total = Number(response.data.total)
        tableData.totalPage = response.data.totalPage
        queryParams.pageNum = response.data.pageNum
        queryParams.pageSize = response.data.pageSize
        console.log('23456y', tableData)
      })

};


const uploadConfirmData = ref({
  uuid: '',
  successList: [],
  failList: []
});

const UpLoadDisabled = ref(true)

function handleChange(options) {

  UpLoadDisabled.value = false
  fileList.value = [options.raw ? 1 : null]
  console.log(options)
}

function handleRemoveChange(options) {
  UpLoadDisabled.value = true
}

function handleListExceed() {
  UpLoadDisabled.value = false
}

function handleClick() {
  upload.value?.submit();
  console.log("11111111")
  console.log(upload.value)
}

const beforeUpload = (file) => {
  console.log('beforeupload');
  console.log(file.type);
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
      file.type === 'application/vnd.ms-excel';
  console.log(fileList.value)

  if (!isExcel) {
    ElMessage.error('只能上传xls或xlsx格式的文件，请重新上传');
    return false;
  }

  return true;
};

const importExcel = async ({file}) => {
  const formData = new FormData();
  formData.append("file", file);
  console.log(formData);
  try {
    const {code, data} = await importVerify(formData);
    if (code !== 200) {
      ElMessage.error("请确认上传文件是否正确");
      return;
    }

    showUploadModal.value = false;
    const dataTemp = {
      uuid: data.id,
      successList: data.successList,
      failList: data.failList
    }
    uploadConfirmData.value = dataTemp;
    console.log(uploadConfirmData.value.uuid);
    showUpTableModal.value = true;
  } catch (error) {
    console.log("到这里来了吗")
    console.error(error);
  } finally {
    // 清空upload组件的文件列表
    // upload.value?.clear();
    upload.value?.clearFiles();
    fileList.value = 0;
  }
};

const handleClose = () => {
  showUpTableModal.value = false;
}

const confirmClose = (value) => {
  if (!value && !notNoticeClose.value) {
    notNoticeClose.value = false;
    window.$dialog.warning({
      title: "警告",
      content: `确定删除退出吗？退出后不可再操作此页面`,
      positiveText: "确定",
      negativeText: "取消",
      onPositiveClick: async () => {
        showUpTableModal.value = false;
        getData();
      },
    });
  }
};


</script>
<style scoped>
.table-container {

  table-layout: fixed;
  margin: 10px;
  width: 100%;
  /* 或者指定一个具体的宽度值，如 90% */
  overflow-x: auto;
  display: block;
  /* 或者flex，根据需要调整 */
}

table {
  width: 100%;
  /* 这里的100%是指table-container的宽度，但由于内容超出，将触发滚动条 */
  min-width: 1200px;
  /* 设定一个最小宽度，确保在较宽的屏幕上也能显示完整 */
  table-layout: fixed;
  /* 保持列宽不变 */
}

th,
td {
  /* 可以设置最大宽度，超出则显示省略号 */
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
